
package myEddy.operator;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.concurrent.LinkedBlockingQueue;


import myEddy.tuple.Tuple;

/**
 * Select operator.
 * It simply return the input tuple if the condition matches.
 * 
 * @author Nathan Ramoly
 *
 */
public class Select extends Operator {

	/** Attributes **/
	
	/**
	 * The column to check
	 */
	private String select_column;
	
	/**
	 * The waited value
	 */
	private String select_value;
	
	
	/** Methods **/
	
	/**
	 * Constructor
	 * @param table Table it works on
	 * @param column Column to check
	 * @param value Wanted value
	 */
	public Select(String table, String column, String value)
	{
		//Adding the table of working
		tables = new ArrayList<String>();
		tables.add(table);
		
		//Creating the input list
		input = new LinkedBlockingQueue<Tuple>();
		
		//Column and value
		select_column = column;
		select_value = value;
		
		running = false;
	}
	
	/** 
	 * The main thread.
	 * Read the inputs and deal with them via other methods
	 */
	@SuppressWarnings("static-access")
	@Override
	public void run() {
		
		running = true;
		
		//Check if eddy is set
		if(parent == null)
		{ } //Handle error
		
		while(running)
		{
			//If queue not empty, getting the last one to operate it
			if(input.size() > 0)
			{
				Tuple to_operate = input.poll();
				
				//Operation...
				ArrayList<Tuple> res = Operate(to_operate);
				
				//Sending it to eddy !
				if(res != null)
				{ sendResultTuple(res); }
				
			}
			//If no tuple available, wait for some.
			else
			{
				try {
					Thread.currentThread().sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}		
		//Thread end
	}

	/**
	 * Just check if the tuple match the condition
	 * @param T Tuple to check
	 */
	@Override
	ArrayList<Tuple> Operate(Tuple T) {
		
		//The same, return
		if( T.getElement(select_column).equals(select_value) )
		{ 
			ArrayList<Tuple> ret = new ArrayList<Tuple>();
			ret.add(T);
			return ret;
		}
		//Else, nothing to to
		else
		{ return null; }
	}

	/** 
	 * @return 0 Because it does always the same stuff
	 */
	@Override
	public int getPerfInd() {
		//This operator has nothing to do... maximum efficiency
		return 0;
	}

	/**
	 * Send the result to Eddy and updates the bitmaps according.
	 * @param results ArrayList of tuple to send to Eddy
	 */
	@Override
	void sendResultTuple( ArrayList<Tuple> results ) {
		
		for(int i=0; i<results.size(); i++)
		{
			Tuple T = results.get(i);
			
			//Updating bitmaps
			BitSet TDoneBM = T.getDoneBitmap();
			BitSet TToDoBM = T.getToDoBitmap();
			
			TDoneBM.set(id, true);
			TToDoBM.set(id, false);
			
			T.setDoneBitmap(TDoneBM);
			T.setToDoBitmap(TToDoBM);
			
			//Send to eddy
			parent.getBackTuple(T, id);
		}		
	}

}
